<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changeValue"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="deptTree"
          node-key="id"
          :data="depts"
          :props="defaultProps"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          @current-change="selectNode"
        />
      </div>

      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'addEmployee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>

          <el-button size="mini" @click="showExcelDialog=true">excel导入</el-button>

          <el-button size="mini" @click="exportToExcel">excel导出</el-button>

        </el-row>

        <!-- 表格组件 -->
        <el-table :data="list">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template #default="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <div v-else class="username"> {{ row.username.charAt(0) }} </div>
            </template>
          </el-table-column>

          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="{ row }">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>

          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />

          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>

              <el-button size="mini" type="text" @click="showRole(row.id)">角色</el-button>

              <el-popconfirm title="确认删除该行数据吗？" @onConfirm="delEmployee(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>

            </template>

          </el-table-column>

        </el-table>

        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total, prev, pager, next"
            :total="total"
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            @current-change="changePage"
          />
        </el-row>
      </div>

    </div>
    <!-- 放置导入组件 -->
    <import-excel :show-excel-dialog.sync="showExcelDialog" @uploadSuccess="getEmployeeList" />

    <!-- 角色弹层内容 -->
    <el-dialog :visible.sync="showRoleDialog" title="分配角色">
      <!-- checkbox -->
      <el-checkbox-group v-model="roleIds">
        <!-- 放置n个的checkbox  要执行checkbox的存储值 item.id-->
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>

      <!-- 确认、取消按钮 -->
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="assignRole">确定</el-button>
          <el-button size="mini" @click="showRoleDialog = false">取消</el-button>
        </el-col>
      </el-row>

    </el-dialog>
  </div>

</template>

<script>
import { getDepartmentAPI } from '@/api/department'
import { assignRoleAPI, delEmployeeAPI, exportToExcelAPI, getEmployeeDetailAPI, getEmployeeListAPI, getEnableRoleListAPI } from '@/api/employee'
import { transListToTreeData } from '@/utils'
import FileSaver from 'file-saver'
import ImportExcel from './components/importExcel.vue'

export default {
  name: 'Employee',
  components: { ImportExcel },
  data() {
    return {
      depts: [], // 组织数据
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      // 存储查询参数
      queryParams: {
        departmentId: null,
        page: 1,
        pagesize: 10,
        keyword: '' // 关键字模糊搜索
      },
      list: [],
      total: 0,
      showExcelDialog: false, // 控制excel的弹层显示和隐藏
      roleList: [], // 角色列表
      roleIds: [], // 角色id列表
      showRoleDialog: false, // 控制角色弹层显示和隐藏
      currentUserId: null // 当前用户id
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    async getDepartment() {
      // 递归方法 将列表转化成树形
      // let result = await getDepartment()
      this.depts = transListToTreeData(await getDepartmentAPI(), 0)
      this.queryParams.departmentId = this.depts[0].id
      // 设置选中节点
      // 树组件渲染是异步的 等到更新完毕
      this.$nextTick(() => {
        // 此时意味着树渲染完毕
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      })
      this.getEmployeeList()
    },
    selectNode(node) {
      // console.log(node)
      this.queryParams.departmentId = node.id // 更新部门
      this.queryParams.page = 1 // 重置页码
      this.getEmployeeList()
    },
    async getEmployeeList() {
      const res = await getEmployeeListAPI(this.queryParams)
      console.log('获取员工列表数据', res)
      this.list = res.rows
      this.total = res.total
    },
    changePage(newPage) {
      this.queryParams.page = newPage
      this.getEmployeeList()
    },
    changeValue() {
      // 单位时间内只执行最后一次
      // this的实例上赋值了一个timer的属性
      clearTimeout(this.timer) // 清理上一次的定时器
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 300)
    },
    async exportToExcel() {
      const res = await exportToExcelAPI()
      console.log('员工数据表', res)
      // 使用一个npm包 直接将blob文件下载到本地 file-saver
      // FileSaver.saveAs(blob对象,文件名称)
      FileSaver.saveAs(res, '员工信息表.xlsx') // 下载文件
    },
    async delEmployee(id) {
      await delEmployeeAPI(id)
      if (this.list.length === 1 && this.queryParams.page > 1) this.queryParams.page--
      this.getEmployeeList()
      this.$message.success('删除员工成功')
    },
    async showRole(id) {
      this.roleList = await getEnableRoleListAPI()
      this.currentUserId = id
      // 1. 获取当前员工的角色id列表
      const res = await getEmployeeDetailAPI(id)
      console.log('获取当前员工的角色id列表', res)
      this.roleIds = res.roleIds
      this.showRoleDialog = true
    },
    async assignRole() {
      // 2. 分配角色
      await assignRoleAPI({ roleIds: this.roleIds, id: this.currentUserId })
      this.$message.success('分配角色成功')
      this.showRoleDialog = false
    }
  }
}

</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;

  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }

  .right {
    flex: 1;
    padding: 20px;

    .opeate-tools {
      margin: 10px;
    }

    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
